<?php

class Application_Model_OfferMapper {
	
	protected $_dbTable;
	
	public function setDbTable($dbTable){
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable(){
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Offer');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Offer $offer){
		$data = array(
				'id_product'   => $offer->getId_product(),
				'date_begin' => $offer->getBegin(),
				'date_end' => $offer->getEnd(),
				'price_reduction' => $offer->getPrice_reduction(),
		);
	
		if (null === ($id = $offer->getId())) {
			unset($data['id_offer']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_offer = ?' => $id));
		}
	}
	
	public function find($id, Application_Model_Offer $offer){
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$offer->setId($row->id_offer)
			->setId_product($row->id_product)
			->setBegin($row->date_begin)
			->setEnd($row->date_end)
			->setPrice_reduction($row->price_reduction);
	}
	
	public function fetchAll() {
		$resultSet = $this->getDbTable()->fetchAll();
		$entries   = array();
		foreach ($resultSet as $row) {
			$entry = new Application_Model_Offer();
			$entry->setId($row->id_offer)
				->setId_product($row->id_product)
				->setBegin($row->date_begin)
				->setEnd($row->date_end)
				->setPrice_reduction($row->price_reduction);
			$entries[] = $entry;
		}
		return $entries;
	}
	
	public function fetchAllProductIdsWithOffers(){
		$resultSet = $this->getDbTable()->fetchAll();
		$ids = array();
		foreach ($resultSet as $row) {
			$ids[] = $row->id_product;
		}
		return $ids;
	}
	
	public function delete($id){
		$where = $this->getDbTable()->getAdapter()->quoteInto('id_offer = ?', $id);
		return $this->getDbTable()->delete($where);
	}
}

